#
# 美好世界模块
#


import datetime
import random

from rasa_sdk.executor import CollectingDispatcher
from typing import Text, Dict, Any, List

from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet, SessionStarted, UserUtteranceReverted
from actions import common
import requests
import re
import time


def current_thought(tracker):
    num = tracker.get_slot('thought_3_change_1')
    cur = 'thought_' + str(num)
    text = tracker.get_slot(cur)
    return text


def conversation_rounds(dispatcher,tracker, **type):
    try:
        if common.rediscommon().get(tracker.current_state()['sender_id'] + '-wx-block-module2'):
            r = common.rediscommon()
            userid = tracker.current_state()['sender_id']
            r.set(userid + 'TempTimeSteame', str(time.time()), ex=86400)
            common.rediscommon().delete(tracker.current_state()['sender_id'] + '-wx-block-module2')
            return []
    except:
        pass
    if 'type' in type:
        if type['type'] == 1:
            userid = tracker.current_state()['sender_id']
            conn = common.POOL.connection(shareable=False)
            cursor = conn.cursor()
            cursor.execute(
                "Select * from `user_result` where topic_type=3 and is_end=0 and user_info_id ='" + userid + "' order by create_time desc")
            x = cursor.fetchone()
            sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",is_part_know=1 where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
            common.connectmysql(sql)
            return []

    userid = tracker.current_state()['sender_id']
    conn = common.POOL.connection(shareable=False)
    cursor = conn.cursor()
    cursor.execute(
        "Select * from `user_result` where topic_type=3 and is_end=0 and user_info_id ='" + userid + "' order by create_time desc")
    x = cursor.fetchone()
    if x[18] not in [(),None]:
        r = common.rediscommon()
        try:
            temp = float(r.get(userid + 'TempTimeSteame'))
        except:
            temp = 0
        timenow = time.time()
        c = round(timenow - temp, 3)
        if x[18] == 0.001:
            sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",response_time=" + str(
                c) + " where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
            common.connectmysql(sql)
        else:
            sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",response_time=" + str(x[
                                                                                                                   18] + c) + " where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
            common.connectmysql(sql)
        r.set(userid + 'TempTimeSteame', str(time.time()), ex=86400)
    else:
        r = common.rediscommon()
        r.set(userid + 'TempTimeSteame', str(time.time()), ex=86400)
        sql = "update `user_result` set conversation_rounds=" + str(x[15] + 1) + ",response_time=0.000 where `user_info_id` ='" + userid + "' and `is_end` = 0 and `topic_type` =3 order by create_time desc limit 1;"
        common.connectmysql(sql)
    return []

class part11_1_1_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_1_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_info` where `id` = '" + userid + "';")
            x = cursor.fetchone()
            nickname = x[1]
            names = x[2]
            if nickname is None:
                nickname = ''
            if names is None:
                names = ''
            test_batch = str(x[35])
            sql = "insert into `user_result`(`id`,`user_info_id`,`topic_type`,`name`,`conversation_rounds`,`nick_name`,`test_batch`) values('" + common.getuid() + "','" + userid + "',3,'" + names + "',0,'" + nickname + "',"+str(x[35])+");"
            common.connectmysql(sql)
            cursor.close()
            conn.close()
            conn = common.POOL.connection(shareable=False)
            cursor = conn.cursor()
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
            x = cursor.fetchone()
            sql = "insert into `user_tools_response` (`id`,`user_info_id`,`user_result_id`,`name`,`use_tools`,`nick_name`,`test_batch`) values('" + common.getuid() + "','" + \
                  userid + "','" + x[0] + "','" + names + "','美丽世界','" + nickname + "',"+test_batch+");"
            common.connectmysql(sql)
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x006')
            return [UserUtteranceReverted()]
        finally:
            cursor.close()
            conn.close()
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='我们整日都在工作与学习中忙忙碌碌，经常忘了欣赏身边的风景，你有多久没有驻足停留，欣赏大自然给我们带来的美了？🌱。', buttons=[
            {'payload': '/button_part11_1_2_choose_1', 'title': '好久了', 'life': 1}, ], json_message={"module_type": 2,"word_module_type":7})
        return []


class part11_1_2_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_2_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='幸运的是，我偶然发现了这段精彩的视频，我觉得这真的是一个发人深省的提醒，，提醒我们这个世界有多么大，多么美丽。想看看吗？',
                                 buttons=[
                                     {'payload': '/button_part11_1_3_choose_1', 'title': '当然', 'life': 1},
                                     {'payload': '/button_part11_1_3_choose_2', 'title': '现在不想看', 'life': 1}, ])
        return []


class part11_1_3_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_3_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='', buttons=[
            {'payload': '/button_part11_1_4_choose_1', 'title': '哇哦，也太美了吧', 'life': 1}], json_message={
            "module_type": 2,
            "video": "wonderful_world", })
        return []


class part11_1_3_choose_2(Action):
    def name(self) -> Text:
        return "action_part11_1_3_choose_2"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='没关系！你想转到另一个话题，还是想今天就到此为止？', buttons=[
            {'payload': '/button_part11_1_4_choose_2', 'title': '另一个话题', 'life': 1},
            {'payload': '/button_part11_1_4_choose_3', 'title': '今天不想继续了', 'life': 1}, ])
        return []


class part11_1_4_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_4_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='你也喜欢它我太开心啦！对我来说，这是一个美丽的提醒，一旦现在的危机得到缓解，所有的一切都在等待着我们去探索和享受。', buttons=[
            {'payload': '/button_part11_1_5_choose_1', 'title': '你觉得什么时候会结束呢？', 'life': 1},
            {'payload': '/button_part11_1_5_choose_2', 'title': '同意', 'life': 1}, ])
        return []


class part11_1_4_choose_2(Action):
    def name(self) -> Text:
        return "action_part11_1_4_choose_2"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='⏩好了，让我们继续下一步的工作! ', buttons=[
            {'payload': '/button_part11_1_5_choose_3', 'title': '好耶~', 'life': 1}, ])
        return []


class part11_1_4_choose_3(Action):
    def name(self) -> Text:
        return "action_part11_1_4_choose_3"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        userid = tracker.current_state()['sender_id']
        sql = "update `user_result` set `is_end` = 1,end_time=now() where `user_info_id`='" + userid + "' and `topic_type` = 3 and `is_end` = 0 order by create_time desc limit 1;"
        common.connectmysql(sql)
        dispatcher.utter_message(text='你已完成当天的实验流程')
        dispatcher.utter_message(text='好吧，我希望你能在某处获得一点新鲜空气和阳光。谢谢你今天来找我--我们之后很快还会再聊天的', buttons=[
            {'payload': '/greet', 'title': '拜拜', 'life': 1}, ])
        return []


class part11_1_5_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_5_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(
            text='我不能确定这一点--现在有很多关于我们要保持社交距离多长的辩论。现在，只要试着安慰自己，花还在开，鸟还在飞，美妙的世界还在旋转。总有一天，这一切又会在你的指尖上。', buttons=[
                {'payload': '/button_part11_1_6_choose_1', 'title': '希望这一天早日到来', 'life': 1},
                {'payload': '/button_part11_1_6_choose_1', 'title': '哇哦', 'life': 1}, ])
        return []


class part11_1_5_choose_2(Action):
    def name(self) -> Text:
        return "action_part11_1_5_choose_2"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        dispatcher.utter_message(text='现在，我希望你能从以下事实中得到安慰：花仍然在开，鸟仍然在飞，奇妙的世界仍然在旋转。有一天，这一切将再次在你的指尖上。', buttons=[
            {'payload': '/button_part11_1_6_choose_1', 'title': '希望这一天早日到来', 'life': 1},
            {'payload': '/button_part11_1_6_choose_1', 'title': '哇哦', 'life': 1}, ])
        return []


class part11_1_5_choose_3(Action):
    def name(self) -> Text:
        return "action_part11_1_5_choose_3"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        global user_type, user_days
        a = ['/button_part2_1_choose_1']
        b = ['/into_grateful_thing_input_1', '/button_part5_1_1_choose_1', '/button_part13_1_1_choose_1',
             '/button_build_power']
        c = ['/button_part8_1_1_choose_1', '/button_part9_1_1_choose_1']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            userid = tracker.current_state()['sender_id']
            cursor.execute("Select * from `user_info` where `id` = '" + userid + "'")
            t = cursor.fetchone()
            user_type = t[24]
            user_days = t[27]
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x0204')
        finally:
            cursor.close()
            conn.close()
        if user_days == -1 or user_days >= 7:
            dispatcher.utter_message(text='你想试一试其他的功能吗？',
                                     buttons=[{"payload": random.choice(a + b + c), "title": "好的", "life": 1}])
        elif user_days == 6:
            d = a + b
            d.append('/button_part8_1_1_choose_1')
            dispatcher.utter_message(text='你想试一试其他的功能吗？',
                                     buttons=[{"payload": random.choice(d), "title": "好的", "life": 1}])
        else:
            dispatcher.utter_message(text='你想试一试其他的功能吗？',
                                     buttons=[{"payload": random.choice(a + b), "title": "好的", "life": 1}])
        return []


class part11_1_6_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_6_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        # userid = tracker.current_state()['sender_id']
        # conn = common.POOL.connection(shareable=False)
        # cursor = conn.cursor()
        # try:
        #     cursor.execute(
        #         "Select * from `user_info` where `id` = '" + userid + "';")
        #     x = cursor.fetchone()
        #     if x == None:
        #         raise Exception
        #     else:
        #         if x[2] != None:
        #             name_value = x[2]
        #         else:
        #             name_value = ''
        #     sql = "insert into `user_result`(`id`,`user_info_id`,`topic_type`,`name`,`conversation_rounds`) values('" + common.getuid() + "','" + userid + "',3,'" + name_value + "',0);"
        #     common.connectmysql(sql)
        #     cursor.close()
        #     conn.close()
        #     conn = common.POOL.connection(shareable=False)
        #     cursor = conn.cursor()
        #     cursor.execute(
        #         "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
        #     x = cursor.fetchone()
        #     sql = "insert into `user_tools_response` (`id`,`user_info_id`,`user_result_id`,`name`) values('" + common.getuid() + "','" + \
        #           userid + "','" + x[0] + "','" + name_value + "');"
        #     common.connectmysql(sql)
        # except:
        #     dispatcher.utter_message(text='机器人错误 错误码0x006')
        #     return [UserUtteranceReverted()]
        # finally:
        #     cursor.close()
        #     conn.close()
        dispatcher.utter_message(text='今天的聊天让你感觉如何呢？', buttons=[
            {'payload': '/button_part11_1_7_choose_1', 'title': '很好', 'life': 1},
            {'payload': '/button_part11_1_7_choose_1_2', 'title': '不太好', 'life': 1}, ])
        return []


class part11_1_7_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_7_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `is_end` = 0 and `topic_type` = 3 order by create_time desc limit 1;")
            x = cursor.fetchone()
            result_id = x[0]
            if tracker.current_state()['events'][-2]['text'] == '/button_part11_1_7_choose_1':
                sql = "update user_tools_response set `evaluation_wonderful_world_esteem`='很好' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
            if tracker.current_state()['events'][-2]['text'] == '/button_part11_1_7_choose_1_2':
                sql = "update user_tools_response set `evaluation_wonderful_world_esteem`='不太好' where `user_info_id` ='" + userid + "' and `user_result_id` = '" + result_id + "' limit 1;"
            common.connectmysql(sql)
        except:
            dispatcher.utter_message(text='机器人错误 错误码0x050')
            return [UserUtteranceReverted()]
        finally:
            cursor.close()
            conn.close()
        dispatcher.utter_message(text='谢谢你的反馈✅，也谢谢你今天来找我聊天！在这个充满压力的时期，花点时间来照顾自己，你很棒哦。', buttons=[
            {'payload': '/button_part11_1_8_choose_1', 'title': '当然啦！', 'life': 1},
            {'payload': '/button_part11_1_8_choose_1', 'title': '谢谢小E', 'life': 1}, ])
        return []


class part11_1_8_choose_1(Action):
    def name(self) -> Text:
        return "action_part11_1_8_choose_1"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        conversation_rounds(dispatcher,tracker)
        userid = tracker.current_state()['sender_id']
        sql = "update `user_result` set `is_end` = 1,end_time=now() where `user_info_id`='" + userid + "' and `topic_type` = 3 and `is_end` = 0 order by create_time desc limit 1;"
        common.connectmysql(sql)
        dispatcher.utter_message(text='你已完成当天的实验流程')
        dispatcher.utter_message(text='之后再聊哦，先拜拜啦！', buttons=[
            {'payload': '/greet', 'title': '拜拜', 'life': 1}, ])
        return []
